package org.example.demo01.web;

import java.util.stream.Collectors;
import java.util.stream.StreamSupport;

import jakarta.validation.Valid;
import org.example.demo01.data.IngredientRepository;
import org.example.demo01.data.TacoRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.*;

import lombok.extern.slf4j.Slf4j;
import org.example.demo01.Ingredient;
import org.example.demo01.TacoOrder;
import org.example.demo01.Ingredient.Type;
import org.example.demo01.Taco;

@Slf4j
@Controller
@RequestMapping("/design")
@SessionAttributes("tacoOrder")
public class DesignTacoController {

    private final IngredientRepository ingredientRepo;
    private final TacoRepository tacoRepository;

    @Autowired
    public DesignTacoController(IngredientRepository ingredientRepo, TacoRepository tacoRepository) {
        this.ingredientRepo = ingredientRepo;
        this.tacoRepository = tacoRepository;
    }

    // 确保在 session 中添加 tacoOrder
    @ModelAttribute("tacoOrder")
    public TacoOrder tacoOrder() {
        return new TacoOrder();
    }

    @ModelAttribute
    public void addIngredientsToModel(Model model) {
        Iterable<Ingredient> ingredients = ingredientRepo.findAll();

        Type[] types = Ingredient.Type.values();
        for (Type type : types) {
            model.addAttribute(type.toString().toLowerCase(),
                    filterByType(ingredients, type));
        }
    }

    @GetMapping
    public String showDesignForm(Model model) {
        Taco taco = new Taco();
        model.addAttribute("taco", taco);
        log.info("添加的 taco 对象: {}", taco);
        log.info("当前模型内容: {}", model.asMap()); // 打印所有 key 和 value
        return "design";
    }

    @PostMapping
    public String processTaco(@Valid @ModelAttribute("taco") Taco taco, Errors errors, @ModelAttribute("tacoOrder") TacoOrder tacoOrder) {
        if (errors.hasErrors()) {
            return "design";
        }

        tacoOrder.addTaco(taco);  // 添加 taco 到 tacoOrder 中
        log.info("添加的 taco: {}", taco);
        log.info("当前的 tacoOrder: {}", tacoOrder);
        log.info("当前 taco 数量: {}", tacoOrder.getTacos().size());  // 打印当前 taco 数量Order: {}", tacoOrder);
        return "redirect:/orders/current";
    }


    private Iterable<Ingredient> filterByType(
            Iterable<Ingredient> ingredients, Type type) {
        return StreamSupport.stream(ingredients.spliterator(), false)
                .filter(x -> x.getType().equals(type))
                .collect(Collectors.toList());
    }
}
